<template>
    <div class="loginbox">
        <div class="mask" @click="showStore.isShowLoginModal = false"></div>
        <div class="login">
            <!-- 关闭按钮 -->
            <div class="close" @click="showStore.isShowLoginModal = false"></div>
            <!-- 导航切换 -->
            <section>
                <a href="javascript:;" :class="{ active: isShowLogin }" @click="isShowLogin = true">手机号码登录</a>
                |
                <a href="javascript:;" :class="{ active: !isShowLogin }" @click="showQrCode">微信扫码登录</a>
            </section>
            <div class="content">
                <div class="phonelogin" v-if="isShowLogin">
                    <div class="row" v-if="isHide">
                        <input type="text" placeholder="请输入手机号" v-model="phoneNumber" />
                    </div>
                    <div class="row" @mouseover="changeHide" @mouseleave="changeShow">
                        <!-- 验证码 -->
                        <touch-verify-code @success="onSuccess" @failed="onFailed" @refresh="onRefresh" />
                    </div>
                    <div class="row" v-if="isHide">
                        <input type="text" placeholder="请输入短信验证码" v-model="verification" />
                        <button class="btn btncode" @click="getCode" v-show="!isShowCode">
                            获取验证码
                        </button>
                        <button class="btn btncode" v-show="isShowCode">
                            {{ count }}
                        </button>
                    </div>
                    <div class="row">
                        <button class="btn btnlogin" @click="submitFn">登录</button>
                    </div>
                </div>
                <div class="qrlogin" v-show="!isShowLogin" id="weixin"></div>
            </div>
        </div>
    </div>
</template>

<script setup lang='ts'>
import { useShowStore } from "@/store/showModal"
import { useStore } from "@/store/user"
import { ref } from "vue";
import TouchVerifyCode from "./Verifycode/TouchVerifyCode.vue";
import { useRoute } from "vue-router"
import { validatePhoneNumber } from "@/utils/index";
import { ElMessage } from 'element-plus'
import { PhoneReginAPI, SendSMSAPI,BindingAPI,WeiXinLoginAPI } from "@/request/api/index"

const showStore = useShowStore()
const store = useStore()
const isShowLogin = ref(true)
// 手机号
const phoneNumber = ref('')
const isHide = ref(true)
const route = useRoute()
// 验证码
const verification = ref('')
const isShowCode = ref(false)
// 验证成功为1 失败为0
const successfully = ref(0)
const count = ref(60)

const changeHide = () => {
    isHide.value = false
}

const changeShow = () => {
    isHide.value = true
}

const onSuccess = (time: number) => {
    console.log("验证成功", time);
    successfully.value = 1
};

const onFailed = () => {
    console.log("验证失败");
};

const onRefresh = () => {
    console.log("图片刷新成功")
    successfully.value = 0
}

// 微信登陆
const showQrCode = () => {
    isShowLogin.value = false;
    //获取二维码 并展示
    // 申请微信登录二维码
    let obj =new WxLogin({
        id: "weixin",
        appid: "wx67cfaf9e3ad31a0d", // 这个appid要填死
        scope: "snsapi_login",
        // 扫码成功后重定向的接口
        redirect_uri: "https://sc.wolfcode.cn/cms/wechatUsers/shop/PC",
        // state填写编码后的url
        state: encodeURIComponent(
            window.btoa("http://127.0.0.1:5173" + route.path)
        ),
        // 调用样式文件
        href: "data:text/css;base64,LmltcG93ZXJCb3ggLnRpdGxlLA0KLmltcG93ZXJCb3ggLmluZm8gew0KICAgIGRpc3BsYXk6IG5vbmU7DQp9DQoNCi5pbXBvd2VyQm94IHFyY29kZSB7DQogICAgbWFyZ2luLXRvcDogMjBweDsNCn0=",
    });
}

// 校验手机号码和滑块验证码（功能 -- 人）
const toVerify = () => {
    if (!validatePhoneNumber(phoneNumber.value)) {
        ElMessage.error('请输入正确的手机号码格式')
        return;
    }
    if (!successfully.value) {
        ElMessage.error('请验证滑块')
        return
    }
    return true;

}

// 获取验证码
const getCode = () => {
    if (!toVerify()) return; //如果res为undefined
    // 3.获取验证码(发送请求给后台)，页面需要倒计时效果
    SendSMSAPI({
        phone: phoneNumber.value
    }).then(res => {
        if (res.code === 0) {
            isShowCode.value = true;
            let timer = setInterval(() => {
                count.value--;
                if (count.value == 0) {
                    clearInterval(timer);
                    count.value = 60;
                    isShowCode.value = false;
                }
            }, 1000);
        }
    });
}

// 点击登陆
async function submitFn() {
    // 1.验证手机号
    // 2.验证滑块验证码
    if (!toVerify()) return;
    // 3.判断短信验证码(只做非空判断，因为接口没有返回验证码)
    if (!verification.value.trim()) {
        ElMessage.error('请输入短信验证码')
        return;
    }
    let uuid = localStorage.getItem("uuid");
        console.log("uuid:",uuid);
        let res = null;
        if(uuid){
            res = await BindingAPI({
        verifyCode: verification.value,
        phone: phoneNumber.value,
            uuid,
            })
            console.log("准备发请求");
        }else{
            console.log("普通手机号码登录请求");
        // 发起手机号码登录请求
        res = await PhoneReginAPI({
        verifyCode: verification.value,
        phone: phoneNumber.value
    })
        }
    
   

    if (!res) return
    // 1.提示
    ElMessage.success('登陆成功!')
    // 2.隐藏登录框
    showStore.isShowLoginModal = false
    // 3.存储token(登录凭证，后续请求用户信息等需要用到)
    localStorage.setItem("x-auth-token", res["x-auth-token"]);
    // 4.切换按钮(显示购物车按钮) -- 一个写
    // 把当前的登录状态设置为true
    store.isLogined = true

    store.registerUser()
}

</script>

<style scoped lang="less">
.loginbox {
    width: 100%;
    height: 100%;
    position: fixed;
    left: 0;
    top: 0;

    .mask {
        width: 100%;
        height: 100%;
        background: rgba(0, 0, 0, 0.5);
    }

    .login {
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        margin: auto;
        width: 555px;
        height: 423px;
        background: url("../assets/img/login-box-bg.png");

        .close {
            position: absolute;
            right: 60px;
            top: 15px;
            width: 22px;
            height: 22px;
            background: url("../assets/img/close.png");
        }

        section {
            line-height: 40px;
            text-align: center;
            padding-top: 40px;

            a {
                text-decoration: none;
                color: #000;

                &.active {
                    color: red;
                }
            }
        }
    }

    .content {
        width: 350px;
        margin: 0 auto;
        text-align: center;

        // background: pink;
        .phonelogin {
            margin-top: 20px;

            .row {
                display: flex;
                margin-bottom: 20px;

                :deep(.verify-code-wrap) {
                    width: 100%;
                    position: relative;
                    box-sizing: border-box;

                    canvas {
                        display: none;

                        left: 0;
                        // top: -120px;
                        // display: none;
                        // width: 100%;
                        // box-sizing: border-box;
                    }

                    &:hover {
                        canvas {
                            display: block;
                        }
                    }
                }

                input {
                    flex: 1;
                    height: 45px;
                    text-indent: 1em;
                }

                .btn {
                    background-color: rgb(10, 50, 142);
                    color: #fff;
                    border: none;
                }

                .btncode {
                    width: 100px;
                    margin-left: 10px;
                }

                .btnlogin {
                    width: 100%;
                    height: 45px;
                }
            }
        }
    }
}
</style>
